<template>
    <el-form ref="loginForm" :model="form" :rules="loginRules" label-width="0" size="large" @keyup.enter="onLogin">
        <el-form-item prop="username">
            <el-input v-model="form.username" :placeholder="t('login.userPlaceholder')" clearable prefix-icon="el-icon-user"/>
        </el-form-item>
        <el-form-item prop="password">
            <el-input v-model="form.password" :placeholder="t('login.PWPlaceholder')" clearable prefix-icon="el-icon-lock" show-password/>
        </el-form-item>
        <el-form-item class="login-captcha" prop="captcha">
            <el-input v-model="form.captcha" placeholder="请输入验证码" prefix-icon="el-icon-key" style="width: 100%">
                <template #append>
                    <el-image :src="captchaBase64" style="width: 100%; height: 100%;" @click="onCaptcha"/>
                </template>
            </el-input>

        </el-form-item>
        <el-form-item style="margin-bottom: 10px;">
            <el-col :span="12">
                <el-checkbox v-model="form.remember" :label="t('login.rememberMe')"></el-checkbox>
            </el-col>
            <el-col :span="12" class="login-forgot">
                <router-link to="/password">{{ t('login.forgetPassword') }}？</router-link>
            </el-col>
        </el-form-item>
        <el-form-item>
            <el-button :loading="isLogin" round style="width: 100%;" type="primary" @click="onLogin">
                {{ t('login.signIn') }}
            </el-button>
        </el-form-item>
        <div class="login-reg">
            {{ t('login.noAccount') }}
            <router-link to="/register">{{ t('login.createAccount') }}</router-link>
        </div>
    </el-form>
</template>

<script lang="ts" setup>
import {onMounted, reactive, ref} from 'vue'
import store from '@/store'
import {useI18n} from 'vue-i18n'
import {useRouter} from 'vue-router'
import {ElNotification} from 'element-plus'
import {service} from "@/utils";

interface LoginInfo {
    username: string;
    password: string;
    uuid?: string;
    captcha?: string;
    remember: boolean;
    clientId: string;
    grantType: string;
}

const router = useRouter()
const {t} = useI18n()
const loginForm = ref()
const captchaBase64 = ref()
const isLogin = ref(false)

const form = reactive<LoginInfo>({
    username: store.userStore.user?.username,
    password: '1234qwer',
    remember: store.userStore.remember,
    clientId: 'e5cd7e4891bf95d1d19206ce24a7b32e',
    grantType: 'password',
})

const loginRules = ref({
    username: [{required: true, message: t('login.userError'), trigger: 'blur'}],
    password: [{required: true, message: t('login.PWError'), trigger: 'blur'}],
    captcha: [{required: true, message: '请输入验证码', trigger: 'blur'}]
})

onMounted(() => {
    onCaptcha()
})
const {VITE_APP_API_BASE_URL} = import.meta.env;
const onCaptcha = async () => {
    form.uuid = `v${Math.random()}`
    captchaBase64.value = `${VITE_APP_API_BASE_URL}/captcha.jpg?uuid=${form.uuid}`;
}

const onLogin = () => {
    loginForm.value.validate((valid: boolean) => {
        if (valid) {
            isLogin.value = true
            // 用户登录
            service.post('/login', form).then(({data}) => {
                store.userStore.setUser(data.user);
                store.userStore.setToken(data.token);
                store.userStore.setRemember(Boolean(form.remember));
                //跳转到手机登录
                let match = /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i;
                if (navigator.userAgent.match(match)) {
                    console.log('手机登录')
                } else {
                    router.push({path: router.currentRoute.value.query.replace || '/'} as any)
                    ElNotification({
                        title: '登录成功!',
                        type: 'success',
                        message: `欢迎回来，${form.username}`
                    });
                }
            }).catch(() => {
                onCaptcha();
            }).finally(() => isLogin.value = false)
        }
    })
}
</script>

<style lang="scss" scoped>
.login-captcha {
    :deep(.el-input) {
        width: 200px;
    }

    img {
        margin-left: 20px;
    }

    :deep(.el-input-group__append) {
        padding: 0;
    }
}
</style>
